package com.wdy.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //1.从redis查询缓存
        String shopTypeJson = stringRedisTemplate.opsForValue().get("cache:shop:type");

        //2.存在直接返回
        if (StrUtil.isNotBlank(shopTypeJson)) {
            return Result.ok(JSONUtil.toList(shopTypeJson, ShopType.class));
        }
        if("".equals(shopTypeJson)){
            return Result.fail("店铺不存在");
        }

        //3.不存在，从数据库查询
        List<ShopType> shopTypes = query().orderByAsc("sort").list();

        //4.数据库里没有,返回错误
        if (shopTypes==null){
            stringRedisTemplate.opsForValue().set("cache:shop:type", "",1, TimeUnit.MINUTES);
        }

        //5.存在，写入缓存
        stringRedisTemplate.opsForValue().set("cache:shop:type", JSONUtil.toJsonStr(shopTypes),30, TimeUnit.MINUTES);

        //6.返回
        return Result.ok(shopTypes);
    }
}
